# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
BadCase录音
"""
from minio import Minio
from requests import session
from util import (
    query_es,
    es_ip,
    es_port,
    baidu_minio_address,
    baidu_minio_access_key,
    baidu_minio_secret_key,
    old_minio_address,
    old_minio_access_key,
    old_minio_secret_key,
    excel_save_dir,
)


class ExportBadCaseMP3:
    def __init__(self, ui_data):
        self.data_date = ui_data.get("data_date")
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        self.company_id = ui_data.get("company_id")
        self.business_id = ui_data.get("business_id")
        self.target_datas = ui_data.get("target_datas")
        self.es_index = f"yicall_{self.company_id}_{self.business_id}_callout_session_ach_{self.data_date}"
        self.baidu_minio_client = Minio(
            baidu_minio_address,
            baidu_minio_access_key,
            baidu_minio_secret_key,
            secure=False,
        )
        self.old_minio_client = Minio(
            old_minio_address,
            old_minio_access_key,
            old_minio_secret_key,
            secure=False,
        )

    def query_voice_address(self):
        fields = ["sourceVoiceRingAddress", "customerCaseId", "sessionId"]
        body = {
            "query": {
                "bool": {
                    "must": [
                        {"match": {"calloutConnectStatus": "100"}},
                        {"terms": {"customerCaseId.keyword": self.target_datas}},
                    ]
                }
            }
        }
        result = query_es(self.es_index, body, fields, ip=es_ip, port=es_port)
        return result

    def export(self):
        """"""
        mp3_names = list()
        es_data = self.query_voice_address()
        if len(es_data) == 0:
            msg = (
                f"⚠️ <font color='red'>**{self.business}**</font>的<font color='green'>{self.data_type}</font>导出失败。"
                f"原因：\n<font color='blue'>在{self.data_date}没有查询到{self.call_type}数据！</font>"
            )
            return {"code": 1, "excel_names": None, "msg": msg}
        else:
            for single_data in es_data:
                voice_address = single_data.get("sourceVoiceRingAddress")
                voice_address_split = voice_address.split("/")
                voice_format = voice_address_split[-1].split(".")[-1]
                case_id = single_data.get("customerCaseId")
                session_id = single_data.get("sessionId")
                # 走百度云minio下载
                if voice_address_split[0].startswith("http"):
                    bucket_name = voice_address_split[2].split(".")[0]  # 获得桶名称
                    target_name = "/".join(voice_address_split[3:])
                    file_content = self.baidu_minio_client.get_object(
                        bucket_name, target_name
                    ).read()
                else:
                    bucket_name = voice_address_split[0]  # 获得桶名称
                    target_name = "/".join(voice_address_split[1:])
                    file_content = self.old_minio_client.get_object(
                        bucket_name, target_name
                    ).read()
                file_name = f"{case_id}-{session_id}.{voice_format}"
                with open(rf"{excel_save_dir}/{file_name}", "wb") as file:
                    file.write(file_content)
                mp3_names.append(file_name)
            return {"code": 0, "excel_names": mp3_names, "msg": None}


if __name__ == "__main__":
    ...
